#include <libpq-fe.h>
#include <iostream>
#include <string>
#include "pgsql.h"
#include <chrono>
#include <fstream>
#include <vector>
#include "table.h"
#include "predicate.h"
#include "tracebit.h"

using namespace std;

//database-config
const char* hostaddr = "localhost";
const char* port = "5432";
const char* dbname = "tpch0001";
const char* user = "postgres";
const char* password = "";


time_t GetCurrentTimeMsec() {
	auto time = chrono::time_point_cast<chrono::milliseconds>(chrono::system_clock::now());
	time_t timestamp = time.time_since_epoch().count();
	return timestamp;
}


void Stringsplit(const string& str, const char split, vector<string>& res)
{
	if (str == "")		return;
	string strs = str + split;
	size_t pos = strs.find(split);

	while (pos != strs.npos)
	{
		string temp = strs.substr(0, pos);
		res.push_back(temp);
		strs = strs.substr(pos + 1, strs.size());
		pos = strs.find(split);
	}
}

PGconn* conn;

int main(int argc,char* argv[]) {
	
	time_t t_begin = GetCurrentTimeMsec();

	PGsql pgsql(hostaddr, port, dbname, user, password);
	
	conn = pgsql.getConn();

	string sql1 = "select ps_supplycost,ps_partkey,ps_suppkey from partsupp order by ps_suppkey";
	vector<string> col_names1 = { "ps_supplycost","ps_partkey","ps_suppkey" };
	Table t1;
	t1.input_data(conn, "partsupp", sql1, col_names1);
	//t1.add_tracebit();
	t1.table_print(10);

	string sql2 = "select s_suppkey from supplier order by s_suppkey";
	vector<string> col_names2 = { "s_suppkey" };
	Table t2;
	t2.input_data(conn, "supplier", sql2, col_names2);
	t2.add_tracebit();
	t2.table_print(10);

	Table t3;
	t3.table_foreignkey_join(t1, "ps_suppkey", t2, "s_suppkey", t3);
	t3.table_print(10);
	t3.orderby_Col("ps_partkey");

	string sql4 = "select p_partkey from part order by p_partkey";
	vector<string> col_names4 = { "p_partkey" };
	Table t4;
	t4.input_data(conn, "part", sql4, col_names4);
	t4.add_tracebit();
	t4.table_print(10);

	Table t5;
	t5.table_foreignkey_join(t3, "ps_partkey", t4, "p_partkey", t5);
	t5.table_print(10);

	TupleSense ts;
	ts.all_tables.push_back(t2);
	ts.all_tables.push_back(t4);
	ts.all_tables.push_back(t5);
	ts.sense_tables.push_back("supplier");
	ts.sense_tables.push_back("part");
	ts.computeTupleSense(t5, "ps_supplycost", t5);

	time_t t_end = GetCurrentTimeMsec();

	cout << "[Timecost] timecost : " << (t_end - t_begin) << endl;

	
}

